package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.user.UserConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页检查
        dto.checkParam();
        //分页查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageParam = new Page(dto.getPage(), dto.getSize());
        IPage<ApUserRealname> page = page(pageParam, wrapper);
        //返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(),  page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证id 不能为空");
        }
        if (checkStatus(status)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证的状态不是待审核状态");
        }
        //修改认证用户状态
        ApUserRealname apUserRealname = ApUserRealname.builder().id(dto.getId()).status(status).build();
        if (dto.getMsg() != null) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //审核状态通过
        if (status.equals(UserConstants.PASS_AUTH)) {
            //创建自媒体账户
            WmUser wmUser = createWmUser(dto);
            //创建作者
            createAuthor(wmUser);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 创建自媒体账户
     *
     * @param dto
     * @return
     */
    private WmUser createWmUser(AuthDto dto) {
        Integer id = dto.getId();
        ApUserRealname apUserRealname = getById(id);
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null) {
            return null;
        }
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if (wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "自媒体账户已存在");
        }
        wmUser = WmUser.builder().build();
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setApUserId(apUser.getId());
        wmUser.setCreatedTime(new Date());
        wmUser.setStatus(9);
        wemediaFeign.save(wmUser);
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        return wmUser;
    }
    /**
     * 创建作者
     *
     * @param wmUser
     * @return
     */
    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUserId);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }
        ApAuthor apAuthor = result.getData();
        if (apAuthor != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "作者用户已存在");
        }
        apAuthor = ApAuthor.builder().name(wmUser.getName())
                .createdTime(new Date())
                .userId(apUserId)
                .type(UserConstants.AUTH_TYPE).build();
        wmUser.setApAuthorId(apAuthor.getId());
        articleFeign.save(apAuthor);
    }
    /**
     * 检查状态
     *
     * @param status
     * @return
     */
    private boolean checkStatus(Short status) {
        if (status == null || (!status.equals(UserConstants.FAIL_AUTH) && !status.equals(UserConstants.PASS_AUTH))) {
            return true;
        }
        return false;
    }
}
